/*
 * MainServerProtocol.java
 *
 * Created on August 10, 2006, 11:24 PM
 *
 */
package org.letva.copie.mainserver;

import java.util.*;
import org.letva.copie.common.message.Message;
import org.letva.copie.common.message.MessageConstants;
import org.letva.copie.common.message.SubServerInfo;

/**
 *
 * @author Vuk Nikolic
 */
public class MainServerProtocol {

	/** Creates a new instance of MainServerProtocol */
	public MainServerProtocol(MainServer ms) {
		myMainServer = ms;
	}

	public Object processInput(Object m) {
		// rezultat koji cemo vratiti nazad

		Object inputMessage = (Message) m;
		Object reply = new Message(MessageConstants.SERVER, ((Message) inputMessage).getSender(), "ServerResponse");
		if (((Message) inputMessage).getInfo() instanceof java.lang.String) {
			String s = (String) ((Message) inputMessage).getInfo(); // string koji je poslao sender

			if (s.equals(MessageConstants.LIST)) {
				// dohvatamo sve subServere i saljemo ih nazad
				Object messages = this.getSubServerLinkedList();
				System.out.println("SALJEMO PORUKU: " + messages);
				reply = new Message(MessageConstants.SERVER, ((Message) inputMessage).getSender(), messages);

			}
			if (s.equals(MessageConstants.STOP_SUBSERVER)) {
				reply = new Message(MessageConstants.SERVER, ((Message) inputMessage).getSender(), MessageConstants.STOP_SUBSERVER);
			}
			if (s.equals(MessageConstants.STOP_MAINSERVER)) {
				reply = new Message(MessageConstants.SERVER, ((Message) inputMessage).getSender(), MessageConstants.STOP_MAINSERVER);
			}
		}

		if (((Message) inputMessage).getInfo() instanceof SubServerInfo) {
			Map<String, SubServerInfo> ss = myMainServer.getSubServers();
			Object ssi = (SubServerInfo) ((Message) inputMessage).getInfo();

			// po defaultu ce HashMap.put() da staru vrednost zameni sa novom
			// pa nema razloga da brisem stari SubServerInfo
			myMainServer.addSubServer((SubServerInfo) ssi);

			Object messages = this.getSubServerLinkedList();
			reply = new Message(MessageConstants.SERVER, ((Message) inputMessage).getSender(), messages);
		}
		return reply;
	}

	private Object getSubServerLinkedList() {
		Map<String, SubServerInfo> ss = myMainServer.getSubServers();
		Object messages = new LinkedList();
		List ll = new LinkedList();

		Set entries = ss.entrySet();
		Iterator entryIter = entries.iterator();
		while (entryIter.hasNext()) {
			Map.Entry entry = (Map.Entry) entryIter.next();
			Object value = entry.getValue();  // Get the value.
			ll.add(value);
		}

		messages = ll;
		return messages;
	}
	private MainServer myMainServer = null;
}
